package com.zkthink.ceres.common.utils;

import com.alibaba.fastjson.JSON;
import net.sf.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName WxQrCodeUtil
 * @Description: WxQrCodeUtil
 * @Author ck
 * @Date 2022/2/9
 * @Version V1.0
 **/
public class WxQrCodeUtil {


    private static final String APPID = "wxf4a8878f92ed4327";
    private static final String APPSECRET = "afb548b0ae25a5c90c0c713fa798e425";

    public static Map<String, String> getAccessToken() throws Exception {
        String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                + APPID + "&secret=" + APPSECRET;
        System.out.println("URL for getting accessToken accessTokenUrl=" + accessTokenUrl);

        URL url = new URL(accessTokenUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.connect();
        //获取返回的字符
        InputStream inputStream = connection.getInputStream();
        int size = inputStream.available();
        byte[] bs = new byte[size];
        inputStream.read(bs);
        String message = new String(bs, "UTF-8");

        //获取access_token
        JSONObject jsonObject = JSONObject.fromObject(message);
        String accessToken = jsonObject.getString("access_token");
        String expires_in = jsonObject.getString("expires_in");
        Map<String, String> map = new HashMap<>();
        System.out.println("accessToken=" + accessToken);
        System.out.println("expiresIn=" + expires_in);
        map.put("accessToken", accessToken);
        map.put("expiresIn", expires_in);
        return map;
    }

    public static String getminiqrQr(String sceneStr, String page, String accessToken, String picPath) {
        //随机数代表图片名
        Integer qrcodeId = (int) (1 + Math.random() * (1000 - 1 + 1));
        String urlQrCode = "";
        String urls = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + accessToken;
        Map<String, Object> param = new HashMap<>();
        //orgId:页面携带的参数
        param.put("scene", sceneStr);
        param.put("path", page);
        param.put("width", 430);
        param.put("auto_color", false);
        param.put("is_hyaline", false);
        Map<String, Object> line_color = new HashMap<>();
        line_color.put("r", 0);
        line_color.put("g", 0);
        line_color.put("b", 0);
        param.put("line_color", line_color);
        System.out.println("调用生成微信URL接口传参:" + param);
        System.out.println("调用生成微信URL接口:" + urls);
        try {
            URL url = new URL(urls);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            httpURLConnection.setConnectTimeout(10000);//连接超时 单位毫秒
            httpURLConnection.setReadTimeout(10000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            printWriter.write(JSON.toJSONString(param));
            // flush输出流的缓冲
            printWriter.flush();
            //开始获取数据
            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
//            File file = new File("C:/Users/wangqiulin/Desktop/1.png");

            int index = picPath.lastIndexOf('/');
            if (index == -1) {
                index = picPath.lastIndexOf('\\');
            }
            String dir = picPath.substring(0, index);
            File dirFile = new File(dir);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }

            File file = new File(picPath);
            if (!file.exists()) {
                file.createNewFile();
            }
            OutputStream os = new FileOutputStream(file);
            int len;
            //设置缓冲写入
            byte[] arr = new byte[2048];
            while ((len = bis.read(arr)) != -1) {
                os.write(arr, 0, len);
                os.flush();
            }
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return picPath;
    }

}
